<template>
  <div class="chat-page">
    <!-- 左侧边栏 -->
    <div class="sidebar">
      <div class="logo-container">
        <div class="logo-header">
          <message-outlined class="logo-icon" />
          <span class="logo-text">AI摄影助手</span>
        </div>
      </div>
      <div class="new-chat-button-container">
        <a-button @click="startNewChat" class="new-chat-button">
          <comment-outlined class="chat-icon" />
          开启新对话
        </a-button>
      </div>
      <div class="history-container" @scroll="handleScroll">
        <template v-for="(group, groupName) in groupedHistory" :key="groupName">
          <div class="history-group-title">{{ groupName }}</div>
          <a-list :data-source="group" class="history-list">
            <template #renderItem="{ item }">
              <a-list-item
                :class="['history-item', { active: activeHistoryId === item.conversationId }]"
                @click="selectHistory(item)"
              >
                <!-- 标题编辑模式 -->
                <template v-if="editingItemId === item.conversationId">
                  <a-input
                    ref="titleInputRef"
                    v-model:value="editingTitle"
                    class="title-input"
                    @pressEnter="saveTitle(item.conversationId)"
                    @blur="saveTitle(item.conversationId)"
                  />
                </template>
                <!-- 普通显示模式 -->
                <template v-else>
                  <div class="history-item-content">
                    <message-outlined class="history-icon" />
                    <span class="history-title">{{ item.title || '新对话' }}</span>
                  </div>
                  <div class="history-item-actions">
                    <a-dropdown :trigger="['click']" @click.stop>
                      <more-outlined class="more-icon" @click.stop />
                      <template #overlay>
                        <a-menu>
                          <a-menu-item @click.stop="startRenaming(item)">
                            <edit-outlined />
                            <span>重命名</span>
                          </a-menu-item>
                          <a-menu-item danger @click.stop="deleteConversation(item.conversationId)">
                            <delete-outlined />
                            <span>删除</span>
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </div>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </template>
        <div v-if="pagination.loading" class="loading-more">
          <a-spin size="small" />
          <span class="loading-text">加载更多...</span>
        </div>
      </div>
      <div class="user-info">
        <a-avatar src="https://api.dicebear.com/7.x/avataaars/svg?seed=user" />
        <span class="user-name">个人信息</span>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-container">
      <!-- 消息列表 -->
      <div class="messages" ref="messagesRef">
        <!-- 欢迎消息 -->
        <div v-if="messages.length === 0" class="welcome-container">
          <div class="welcome-content">
            <div class="logo-placeholder">
              <!-- 预留logo位置 -->
              <img src="/deepseek-avatar.svg" alt="DeepSeek Logo" class="welcome-logo" />
            </div>
            <div class="welcome-message">我是 摄影小助手, 很高兴见到你!</div>
            <div class="welcome-description">
              我可以给你提供摄影知识、摄影技巧、相机选购，请将你的任务交给我吧~
            </div>
          </div>
        </div>

        <!-- 常规消息 -->
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
          v-show="
            !(
              messages.length === 1 &&
              messages[0].role === 'assistant' &&
              messages[0].content === '你好！我是AI助手，有什么可以帮你的吗？'
            )
          "
        >
          <div class="avatar">
            <img :src="message.role === 'user' ? userAvatar : aiAvatar" :alt="message.role" />
          </div>
          <div class="message-content">
            <!-- 添加消息内容长度显示，帮助调试 -->
            <div class="debug-info" v-if="message.content">
              消息长度: {{ message.content.length }}
            </div>
            <!-- 消息内容 -->
            <div v-if="message.role === 'user'" class="message-text">
              {{ message.content }}
            </div>
            <MarkdownRenderer v-else :content="message.content" class="markdown-content" />
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-container">
        <div class="input-area">
          <div class="input-wrapper">
            <a-textarea
              v-model:value="inputMessage"
              placeholder="发送消息 (Enter发送，Shift+Enter换行)"
              :auto-size="{ minRows: 1, maxRows: 4 }"
              @keyup.enter="handleEnterKey"
            />
            <div class="input-actions">
              <button title="添加链接">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
                  <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
                </svg>
              </button>
              <button title="深度思考">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <circle cx="12" cy="12" r="10"></circle>
                  <path d="M12 16v-4"></path>
                  <path d="M12 8h.01"></path>
                </svg>
              </button>
              <button title="技能">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <path
                    d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"
                  ></path>
                </svg>
              </button>
              <button title="剪切">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <circle cx="6" cy="6" r="3"></circle>
                  <circle cx="6" cy="18" r="3"></circle>
                  <line x1="20" y1="4" x2="8.12" y2="15.88"></line>
                  <line x1="14.47" y1="14.48" x2="20" y2="20"></line>
                  <line x1="8.12" y1="8.12" x2="12" y2="12"></line>
                </svg>
              </button>
              <button title="语音">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"></path>
                  <path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
                  <line x1="12" y1="19" x2="12" y2="23"></line>
                  <line x1="8" y1="23" x2="16" y2="23"></line>
                </svg>
              </button>
            </div>
          </div>
          <a-button type="primary" @click="sendMessage" :loading="loading" class="send-button">
            发送
          </a-button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <a-modal
      v-model:open="showDeleteModal"
      :footer="null"
      :closable="true"
      :mask-closable="false"
      width="360px"
      class="delete-modal"
      centered
      @cancel="cancelDelete"
    >
      <div class="delete-modal-content">
        <div class="delete-modal-title">永久删除对话</div>
        <div class="delete-modal-message">删除后，该对话将不可恢复。确认删除吗？</div>
        <div class="delete-modal-actions">
          <a-button class="cancel-btn" type="text" @click="cancelDelete">取消</a-button>
          <a-button class="delete-btn" danger @click="confirmDelete">删除</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import { v4 as uuidv4 } from 'uuid'
import {
  SyncOutlined,
  MessageOutlined,
  MoreOutlined,
  EditOutlined,
  DeleteOutlined,
  CloseOutlined,
  CommentOutlined,
} from '@ant-design/icons-vue'
import {
  getConversationByPage,
  editConversationTitle,
  deleteConversation as deleteConversationApi,
} from '../../api/conversationController'
import { getConversationMsgListVo } from '../../api/conversationMsgController'
import dayjs from 'dayjs'
import MarkdownRenderer from '../../components/MarkdownRenderer.vue'

const router = useRouter()
const route = useRoute()

// 定义消息类型
interface Message {
  role: 'user' | 'assistant'
  content: string
  time: string
}

const messages = ref<Message[]>([])
const inputMessage = ref('')
const loading = ref(false)
const messagesRef = ref<HTMLDivElement>()
const conversationId = ref('')

// 会话列表数据
const chatHistory = ref<
  {
    conversationId?: string
    userId?: number
    title?: string
    createTime?: string
    updateTime?: string
    isDelete?: number
  }[]
>([])

// 分页相关状态
const pagination = ref({
  current: 1,
  pageSize: 18,
  total: 0,
  loading: false,
  hasMore: true,
})

// 获取会话列表数据
const fetchChatHistory = async (isLoadMore = false) => {
  if (pagination.value.loading || (!isLoadMore && !pagination.value.hasMore)) {
    return
  }

  pagination.value.loading = true
  try {
    const res = await getConversationByPage({
      sortField: 'updateTime',
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
    })

    if (res.data.code === 0 && res.data.data?.records) {
      if (isLoadMore) {
        chatHistory.value = [...chatHistory.value, ...res.data.data.records]
      } else {
        chatHistory.value = res.data.data.records
      }

      pagination.value.total = res.data.data.total || 0
      pagination.value.hasMore = chatHistory.value.length < pagination.value.total

      if (pagination.value.hasMore) {
        pagination.value.current++
      }
    } else {
      message.error('获取会话列表失败：' + res.data.message)
    }
  } catch (error: any) {
    message.error('获取会话列表失败：' + error.message)
  } finally {
    pagination.value.loading = false
  }
}

// 监听滚动加载更多
const handleScroll = (e: Event) => {
  const target = e.target as HTMLElement
  const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight
  if (scrollBottom < 50 && !pagination.value.loading && pagination.value.hasMore) {
    fetchChatHistory(true)
  }
}

// 当前活跃的历史记录ID
const activeHistoryId = ref('')

// 头像设置
const userAvatar = 'https://api.dicebear.com/7.x/avataaars/svg?seed=user'
const aiAvatar = 'https://api.dicebear.com/7.x/bottts/svg?seed=ai'

// 添加样式
const markdownStyles = {
  'markdown-content': {
    '& p': {
      margin: '0.5em 0',
    },
    '& code': {
      backgroundColor: '#f5f5f5',
      padding: '2px 4px',
      borderRadius: '3px',
      fontSize: '0.9em',
    },
    '& pre': {
      backgroundColor: '#f5f5f5',
      padding: '1em',
      borderRadius: '5px',
      overflow: 'auto',
    },
    '& blockquote': {
      borderLeft: '4px solid #ddd',
      padding: '0 1em',
      margin: '1em 0',
      color: '#666',
    },
    '& ul, & ol': {
      paddingLeft: '2em',
      margin: '0.5em 0',
    },
  },
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesRef.value) {
    messagesRef.value.scrollTo({
      top: messagesRef.value.scrollHeight,
      behavior: 'smooth',
    })
  }
}

// 处理回车键事件
const handleEnterKey = (e: KeyboardEvent) => {
  // 如果按下了shift键，不发送消息，允许换行
  if (e.shiftKey) return

  // 阻止默认行为（换行）
  e.preventDefault()

  // 发送消息
  sendMessage()
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) {
    return
  }

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: inputMessage.value,
    time: new Date().toISOString(),
  })

  // 清空输入框
  const userMessage = inputMessage.value
  inputMessage.value = ''

  // 检查是否是新对话的第一条消息
  const isFirstMessage =
    messages.value.length === 2 &&
    messages.value[0].role === 'assistant' &&
    messages.value[1].role === 'user'

  // 如果是新对话的第一条消息，将对话添加到历史记录
  if (isFirstMessage) {
    const title = userMessage.length > 20 ? userMessage.substring(0, 20) + '...' : userMessage
    chatHistory.value.unshift({
      conversationId: conversationId.value,
      userId: 0,
      title: title,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      isDelete: 0,
    })
  }

  // 滚动到底部
  await scrollToBottom()

  // 添加 AI 消息占位
  const aiMessageIndex = messages.value.length
  messages.value.push({
    role: 'assistant',
    content: '正在思考...',
    time: new Date().toISOString(),
  })

  // 设置加载状态
  loading.value = true

  try {
    // 使用fetch实现流式渲染，使用完整的后端地址
    const response = await fetch('http://localhost:9494/api/ai/simple/dochat/sse/emitter', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'text/event-stream',
      },
      body: JSON.stringify({
        conversationId: conversationId.value || uuidv4(),
        content: userMessage,
      }),
      credentials: 'include', // 携带cookie
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    if (!response.body) {
      throw new Error('No response body')
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let buffer = ''

    while (true) {
      const { value, done } = await reader.read()
      if (done) break

      buffer += decoder.decode(value, { stream: true })

      // 处理SSE格式的数据
      let lines = buffer.split('\n')
      // 保留最后一行（可能不完整）
      buffer = lines.pop() || ''

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.slice(5) // 移除trim()操作，保留原始内容
          if (data === '[DONE]') continue

          // 安全地检查并更新消息
          if (aiMessageIndex < messages.value.length) {
            const currentMessage = messages.value[aiMessageIndex]
            if (currentMessage.content === '正在思考...') {
              currentMessage.content = data
            } else {
              // 处理空的data行为换行符
              if (data === '') {
                currentMessage.content += '\n'
              } else {
                currentMessage.content += data
              }
            }
            await nextTick()
            await scrollToBottom()
          }
        }
      }
    }
  } catch (error: any) {
    message.error('发送消息失败：' + error.message)

    // 移除失败的消息
    if (aiMessageIndex < messages.value.length) {
      messages.value.splice(aiMessageIndex, 1)
    }
  } finally {
    loading.value = false
    await scrollToBottom()
  }
}

// 选择历史记录
const selectHistory = async (item: { conversationId?: string; title?: string }) => {
  if (!item.conversationId) {
    message.error('会话ID不存在')
    return
  }

  // 更新路由到具体的会话
  await router.push(`/ai/chat/${item.conversationId}`)

  activeHistoryId.value = item.conversationId
  conversationId.value = item.conversationId

  // 加载中提示
  messages.value = [
    {
      content: '正在加载历史消息...',
      role: 'assistant',
      time: new Date().toISOString(),
    },
  ]

  try {
    // 调用API获取历史消息
    const res = await getConversationMsgListVo({
      conversationId: item.conversationId,
      sortField: 'updateTime',
      sortOrder: 'desc',
    })

    if (res.data.code === 0 && res.data.data) {
      const { conversation, conversationMsg } = res.data.data

      // 如果有历史消息，则显示
      if (conversationMsg && conversationMsg.length > 0) {
        // 将后端返回的消息转换为前端显示格式
        messages.value = conversationMsg.map((msg) => ({
          role: msg.role as 'user' | 'assistant',
          content: msg.content || '',
          time: msg.createTime || new Date().toISOString(),
        }))
      } else {
        // 没有历史消息
        messages.value = [
          {
            content: `开始与 "${item.title}" 的对话`,
            role: 'assistant',
            time: new Date().toISOString(),
          },
        ]
      }
    } else {
      message.error('获取历史消息失败：' + (res.data.message || '未知错误'))
      messages.value = [
        {
          content: '获取历史消息失败，请重试',
          role: 'assistant',
          time: new Date().toISOString(),
        },
      ]
    }
  } catch (error: any) {
    message.error('获取历史消息失败：' + error.message)
    messages.value = [
      {
        content: '获取历史消息失败，请重试',
        role: 'assistant',
        time: new Date().toISOString(),
      },
    ]
  } finally {
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 开启新对话
const startNewChat = async () => {
  // 生成新的ID
  const newId = uuidv4()

  // 更新路由到新对话
  await router.push('/ai')

  // 设置为当前活跃对话，但不添加到历史记录
  activeHistoryId.value = newId

  // 清空当前对话
  messages.value = []

  // 设置会话ID
  conversationId.value = newId

  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}

// 编辑会话标题相关变量
const editingItemId = ref('')
const editingTitle = ref('')
const titleInputRef = ref(null)

// 开始重命名会话
const startRenaming = (item: { conversationId?: string; title?: string }) => {
  if (!item.conversationId) return

  editingItemId.value = item.conversationId
  editingTitle.value = item.title || ''

  // 等待DOM更新后聚焦输入框
  nextTick(() => {
    if (titleInputRef.value) {
      // @ts-ignore
      titleInputRef.value.focus()
    }
  })
}

// 保存会话标题
const saveTitle = async (conversationId: string | undefined) => {
  if (!conversationId || !editingTitle.value.trim()) {
    editingItemId.value = ''
    return
  }

  try {
    const res = await editConversationTitle({
      conversationId: conversationId,
      title: editingTitle.value.trim(),
    })

    if (res.data.code === 0 && res.data.data) {
      // 更新本地会话列表中的标题
      const conversation = chatHistory.value.find((item) => item.conversationId === conversationId)
      if (conversation) {
        conversation.title = editingTitle.value.trim()
      }
      message.success('标题已更新')
    } else {
      message.error('更新标题失败：' + res.data.message)
    }
  } catch (error: any) {
    message.error('更新标题失败：' + error.message)
  } finally {
    // 退出编辑模式
    editingItemId.value = ''
  }
}

// 删除会话相关变量
const showDeleteModal = ref(false)
const deletingConversationId = ref('')

// 删除会话
const deleteConversation = (conversationId: string | undefined) => {
  if (!conversationId) return

  // 设置要删除的会话ID并显示确认弹窗
  deletingConversationId.value = conversationId
  showDeleteModal.value = true
}

// 确认删除会话
const confirmDelete = async () => {
  const conversationId = deletingConversationId.value
  if (!conversationId) return

  // 立即关闭弹窗
  showDeleteModal.value = false

  try {
    // 调用删除会话的API
    const res = await deleteConversationApi({
      conversationId: conversationId,
    })

    if (res.data.code === 0 && res.data.data) {
      // 从本地列表中删除
      chatHistory.value = chatHistory.value.filter((item) => item.conversationId !== conversationId)

      // 如果删除的是当前活跃的会话，则开启一个新会话
      if (activeHistoryId.value === conversationId) {
        startNewChat()
      }

      message.success('会话已删除')
    } else {
      message.error('删除会话失败：' + res.data.message)
    }
  } catch (error: any) {
    message.error('删除会话失败：' + error.message)
  } finally {
    // 清空要删除的会话ID
    deletingConversationId.value = ''
  }
}

// 取消删除
const cancelDelete = () => {
  showDeleteModal.value = false
  deletingConversationId.value = ''
}

// 在组件加载时检查路由参数
onMounted(async () => {
  // 重置分页状态
  pagination.value = {
    current: 1,
    pageSize: 18,
    total: 0,
    loading: false,
    hasMore: true,
  }

  // 获取会话列表
  await fetchChatHistory()

  // 检查路由参数中是否有会话ID
  const chatId = route.params.id
  if (chatId && typeof chatId === 'string') {
    // 查找对应的会话
    const conversation = chatHistory.value.find((item) => item.conversationId === chatId)
    if (conversation) {
      // 加载指定的会话
      await selectHistory(conversation)
    } else {
      // 如果找不到对应的会话，跳转到 AI 首页
      await router.push('/ai')
    }
  } else if (route.path === '/ai') {
    // 如果是 AI 首页，开启新对话
    startNewChat()
  }
})

// 组件卸载时清理
onUnmounted(() => {
  const historyContainer = document.querySelector('.history-container')
  if (historyContainer) {
    historyContainer.removeEventListener('scroll', handleScroll)
  }
})

// 计算属性：按时间分组的会话历史
const groupedHistory = computed(() => {
  const groups: { [key: string]: typeof chatHistory.value } = {
    今天: [],
    昨天: [],
    '7天内': [],
    更早: [],
  }

  const now = dayjs()
  const yesterday = now.subtract(1, 'day').startOf('day')
  const sevenDaysAgo = now.subtract(7, 'day').startOf('day')

  chatHistory.value.forEach((item) => {
    const updateTime = dayjs(item.updateTime)

    if (updateTime.isAfter(now.startOf('day'))) {
      groups['今天'].push(item)
    } else if (updateTime.isAfter(yesterday)) {
      groups['昨天'].push(item)
    } else if (updateTime.isAfter(sevenDaysAgo)) {
      groups['7天内'].push(item)
    } else {
      groups['更早'].push(item)
    }
  })

  // 只返回有内容的分组
  return Object.entries(groups)
    .filter(([_, items]) => items.length > 0)
    .reduce((acc, [key, items]) => {
      acc[key] = items
      return acc
    }, {} as { [key: string]: typeof chatHistory.value })
})
</script>

<style scoped>
.chat-page {
  display: flex;
  height: 100vh;
  width: 100%;
  background-color: #f5f5f5;
}

.sidebar {
  width: 260px;
  min-width: 260px;
  height: 100%;
  background-color: #f9fbff;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.logo-container {
  padding: 16px 16px 0;
  display: flex;
  align-items: center;
}

.logo-header {
  display: flex;
  align-items: center;
}

.logo-icon {
  font-size: 18px;
  margin-right: 8px;
  color: #1677ff;
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.new-chat-button-container {
  padding: 36px 36px 16px;
  display: flex;
  justify-content: center;
  border-bottom: 1px solid #e8e8e8;
}

.new-chat-button {
  width: 100%;
  height: 44px;
  border-radius: 22px;
  background-color: #eef5ff;
  color: #eef5ff;
  border: none;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: none;
}

.new-chat-button:hover {
  color: #eef5ff;
  border: none;
}

.chat-icon {
  font-size: 20px;
  margin-right: 4px;
}

.history-container {
  height: 640px;
  overflow-y: auto;
  padding: 0 8px;
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.3) transparent;
}

/* Webkit浏览器的滚动条样式 */
.history-container::-webkit-scrollbar {
  width: 6px;
}

.history-container::-webkit-scrollbar-track {
  background: transparent;
}

.history-container::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.history-container::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.3);
}

.history-group-title {
  margin-top: 18px;
  padding: 8px 12px;
  font-size: 13px;
  font-weight: 600;
  color: #1d1c1c;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 1;
}

.history-list {
  padding: 0;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin: 4px 0;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 16px;
}

.history-item:hover {
  background-color: #f0f0f0;
}

.history-item.active {
  background-color: #e6f4ff;
}

.history-item-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  overflow: hidden;
}

.history-item-actions {
  display: flex;
  align-items: center;
  opacity: 0;
  transition: opacity 0.2s;
  font-size: 16px;
}

.history-item:hover .history-item-actions {
  opacity: 1;
}

.more-icon {
  font-size: 16px;
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.history-icon {
  font-size: 16px;
  color: #999;
  margin-right: 8px;
}

.history-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
  line-height: 18px;
  font-size: 16px;
}

.user-info {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  border-top: 1px solid #e8e8e8;
}

.user-name {
  font-size: 14px;
  color: #666;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.welcome-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
}

.welcome-content {
  text-align: center;
  max-width: 600px;
}

.logo-placeholder {
  margin-bottom: 24px;
}

.welcome-logo {
  width: 120px;
  height: 120px;
}

.welcome-message {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
}

.welcome-description {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
}

.message {
  display: flex;
  margin-bottom: 20px;
  gap: 12px;
}

.user-message {
  flex-direction: row-reverse;
}

.ai-message {
  flex-direction: row;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  max-width: 70%;
  min-width: 50px;
  padding: 12px 16px;
  border-radius: 12px;
  background: #f5f5f5;
  white-space: pre-wrap;
  word-break: break-word;
}

.user-message .message-content {
  background: #e3f2fd;
  margin-left: auto;
}

.ai-message .message-content {
  background: #f5f5f5;
  margin-right: auto;
}

.debug-info {
  font-size: 10px;
  color: #999;
  margin-bottom: 4px;
}

.debug-border {
  border: 1px dashed #ccc;
  min-height: 20px;
}

.markdown-content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  word-break: break-word;
  padding: 4px;
}

.input-container {
  padding: 20px;
  border-top: 1px solid #eee;
  position: relative;
}

.input-area {
  display: flex;
  gap: 12px;
  max-width: 1000px; /* 增加最大宽度 */
  margin: 0 auto;
}

.input-wrapper {
  flex: 1;
  position: relative;
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 12px; /* 增加圆角 */
  transition: all 0.3s;
  min-height: 60px; /* 增加最小高度 */
  padding: 10px; /* 增加内边距 */
}

.input-wrapper :deep(.ant-input) {
  border: none;
  box-shadow: none !important;
  padding: 12px 15px; /* 增加输入框内边距 */
  font-size: 16px; /* 增加字体大小 */
  line-height: 1.5;
}

.input-wrapper :deep(.ant-input:focus) {
  box-shadow: none;
}

:deep(.ant-input-textarea-show-count::after) {
  margin-bottom: 8px;
  margin-right: 8px;
}

.input-actions {
  display: flex;
  gap: 12px; /* 增加按钮间距 */
  padding: 8px;
  align-items: center;
}

.input-actions button {
  padding: 8px; /* 增加按钮大小 */
  background: transparent;
  border: none;
  cursor: pointer;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-actions button:hover {
  color: #1a73e8;
}

:deep(.ant-btn) {
  height: 44px; /* 增加发送按钮高度 */
  padding: 0 24px; /* 增加发送按钮宽度 */
  font-size: 16px; /* 增加发送按钮字体大小 */
  border-radius: 10px;
  background: #1677ff;
  border: none;
}

:deep(.ant-btn:hover) {
  background: #0958d9;
}

/* 删除菜单项样式 */
:deep(.ant-dropdown-menu-item-danger),
:deep(.ant-dropdown-menu-item-danger:hover) {
  color: #ff4d4f;
}

/* 删除确认弹窗样式 */
.delete-modal :deep(.ant-modal-content) {
  padding: 0;
  border-radius: 12px;
  overflow: hidden;
}

.delete-modal :deep(.ant-modal-body) {
  padding: 0;
}

.delete-modal :deep(.ant-modal-close) {
  top: 15px;
  right: 15px;
}

.delete-modal :deep(.ant-modal-close-x) {
  width: 24px;
  height: 24px;
  line-height: 24px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

.delete-modal-content {
  padding: 20px;
}

.delete-modal-title {
  font-size: 20px;
  font-weight: 600;
  color: #000000;
  text-align: left;
  margin-bottom: 16px;
}

.delete-modal-message {
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  margin-bottom: 20px;
}

.delete-modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn {
  color: #000000;
  background-color: #ffffff;
  border: 1px solid #d9d9d9;
}

.cancel-btn:hover {
  color: #000000;
  background-color: #ffffff;
  border-color: #d9d9d9;
}

.delete-btn {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  color: #ffffff;
}

.delete-btn:hover {
  background-color: #ff7875;
  border-color: #ff7875;
  color: #ffffff;
}

.loading-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px;
  border-top: 1px solid #e8e8e8;
}

.loading-text {
  margin-left: 8px;
  font-size: 14px;
  color: #666;
}

.message-text {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
